#!/usr/bin python3
# -*- coding:UTF-8 -*-
# Author:nigo
import plotly.express as px
import json
import pandas as pd

def get_data(path):
    with open(path) as f:
        text = f.read()
    data = json.loads(text)
    metro = process_metro_data(data)
    df = pd.DataFrame(metro)
    return df

def process_metro_data(data):
    """处理地铁数据
    data:json数据
    """
    lon = []
    lat = []
    sname = []
    lname = []
    for line in data['l']:# 循环每条线路
        line_name = line['ln']
        for station in line['st']: # 循环每个站点
            location = station['sl']
            lon.append(float(location.split(',')[0]))
            lat.append(float(location.split(',')[1]))
            station_name = station['n']
            sname.append(station_name)
            lname.append(line_name)
    metro = {
        'line':lname,
        'name':sname,
        'lon':lon,
        'lat':lat,
    }
    return metro

if __name__ == "__main__":
    # 你的token
    token = '你的token'
    # 线路与颜色对应关系
    color = {
        '1号线':'#2249A3',
        '1号线-1':'#2249A3',
        '2号线':'#EE782E',
        '3号线':'#F0087D',
        '4号线':'#00AB4F',
        '5号线':'#96499A',
        '6号线':'#B35A1F',
        '7号线':'#84C3D0',
        '8号线':'#86B81C',
        '9号线':'#D0970A',
        '10号线':'#0065B3',
        '17号线':'#98D1C0',
        '18号线':'#008187',
    }
    # 获取数据
    df = get_data('metro.json')
    # 创建figure对象 （轨迹+画布）
    fig = px.scatter_mapbox(df,lat='lat',lon='lon',color='line',text='name')
    # 更新轨迹 点大小和显示模式(点+线)
    fig.update_traces(mode="markers+lines")
    # 更新每一条轨迹的颜色
    fig.for_each_trace(
        lambda trace:trace.update(marker_color = color[trace.name])
    )
    # 更新样式
    fig.update_layout(mapbox={"accesstoken":token,
                          'center':{
                              'lon':104.072329,'lat':30.65342,},
                          'style':'light',
                          'zoom':11.8},
                  margin={'l':0,'r':0,'t':20,'b':0},
                 )
    # 显示画布
    fig.show()
